package com.xxx.client.android.dialog;

import android.app.Activity;
import android.content.Intent;

import com.xxx.client.android.CustomApplication;
import com.xxx.client.android.activity.ArticleActivity;
import com.xxx.client.android.api.ArticleVO;
import com.xxx.client.android.api.WSError;
import com.xxx.client.android.api.XXXApi;
import com.xxx.client.android.api.impl.XXXApiImpl;
import com.xxx.client.android.db.Database;
import com.xxx.client.android.db.DatabaseImpl;
import com.xxx.client.android.db.History;

public class ArticleLoadingDialog extends LoadingDialog<Integer, ArticleVO> {

	public ArticleLoadingDialog(Activity activity, int loadingMsg, int failMsg) {
		super(activity, loadingMsg, failMsg);
	}

	@Override
	public ArticleVO doInBackground(Integer... params) {

		XXXApi service = new XXXApiImpl();
		ArticleVO article = null;
		try {
			if (params[0] != null) {
				article = service.getArticle(params[0], CustomApplication
						.getInstance().isEmulator());
			} else if (params[1] != null) {
				article = service.getFirstArticle(params[1], CustomApplication
						.getInstance().isEmulator());
			} else {
				// do nothing
				CustomApplication.log("not data");
			}
			if (article != null && params[2] != null) {
				Database database = new DatabaseImpl(mActivity);
				History history = new History();
				history.setHistoryName(article.getTitleName());
				history.setHistoryUrl(article.getArticleId().toString());
				history.setHistoryType(History.INTERNAL);
				database.addHistory(history);
			}
		} catch (RuntimeException e) {
			e.printStackTrace();
			return null;
		} catch (WSError e) {
			publishProgress(e);
			cancel(true);
		}
		return article;

	}

	@Override
	public void doStuffWithResult(ArticleVO article) {

		Intent intent = new Intent(mActivity, ArticleActivity.class);

		intent.putExtra("article", article);
		mActivity.startActivity(intent);
		if (mActivity instanceof ArticleActivity) {
			mActivity.finish();
		}
	}

}
